<script setup>
import { ref, onMounted } from 'vue'
import { ElCard, ElTable, ElTableColumn, ElMessage } from 'element-plus'
import {listRecords, getRecords, delRecords, addRecords, updateRecords} from "@/api/InventoryCheck";
import { listDepartment } from "@/api/department";
import { listAllUser } from "@/api/User";
import {useRoute,useRouter} from "vue-router"
import {Delete, Edit, Plus, Refresh, Search, View} from "@element-plus/icons-vue";
const router = useRouter()
// 弹框状态
const formVisible = ref(false)
const title = ref('')

// 盘点表单数据
const recordForm = ref({
})

// 盘点树形数据
const parentRecords = ref([])
// 用户数据
const allUsers = ref([])

// 是否为编辑状态
const isEditMode = ref(false)

// 当前编辑的盘点ID
const currentRecordId = ref(null)

const allDepartments = ref([])


// // 获取盘点树形结构 与 列表数据
const getRecordsTreeData = () => {
  listRecords({
    type: 0
  }).then(res => {
    if (res.code === 200) {
      parentRecords.value = res.data
    }
  })
}

const getAllUser = () => {
  listAllUser({
    // name: queryForm.value.name
  }).then(res => {
    if (res.code === 200) {
      allUsers.value = res.data
    }
  })
}
// // 获取部门树形结构 与 列表数据
const getDepartmentTreeData = () => {
  listDepartment({
    // name: queryForm.value.name
  }).then(res => {
    if (res.code === 200) {
      allDepartments.value = res.data
    }
  })
}




// 提交盘点表单
const handleSubmit = async () => {
    console.log(recordForm.value,789)
    // 检查盘点名称是否为空
    if (!recordForm.value.name) {
        ElMessage.warning('请输入盘点名称');
        return;
    }
    const apiMethod = isEditMode.value 
        ? updateRecords 
        : addRecords;
  recordForm.value.deptId = recordForm.value.departmentIds.join(",");
    const requestData = { ...{id: currentRecordId.value}, ...recordForm.value, type:0 };
  const result = await apiMethod(requestData)
  if (result.code === 200) {
    ElMessage.success(`${isEditMode.value ? '更新' : '新增'}成功`);
    formVisible.value = false;
    resetForm();
    getRecordsTreeData();
  }
}

// 重置表单
const resetForm = () => {
  isEditMode.value = false;
  currentRecordId.value = null;
  recordForm.value = { name: '', parentId: null, deptCode: '', managerId: null};
}

// 新增盘点
const addRecordsData = () => {
  
  isEditMode.value = false;
  resetForm();
  formVisible.value = true
  title.value = '新增盘点'
}

// 获取盘点树形结构

// 删除盘点
const deleteRecordData = (row) => {
  console.log(row,"删除")
  delRecords(row.id).then(res => {
    if (res.code === 200) {
      ElMessage.success('删除成功')
      getRecordsTreeData()
    }
  }).catch(err => {
    ElMessage.error('删除失败')
  })
}

// 编辑盘点
const editRecordData = (row) => {
  title.value = '编辑盘点'
  resetForm();
  //根据id获取盘点详情
  getRecords(row.id).then(res => {
    console.log(res)
    if (res.code === 200) {
      isEditMode.value = true;
      currentRecordId.value = row.id;
      if (res.data.deptId) {
        res.data.departmentIds = res.data.deptId.split(",")
      }
      recordForm.value = { ...res.data };
      console.log(recordForm.value)
      formVisible.value = true
    }
  })
}


const recordDataDetail = (row) => {
  title.value = '编辑盘点'
  resetForm();
  //跳转到盘点详情页面
  // router.push(`/check-detail/${row.id}`)
  router.push({ path: '/check-asset-detail', query: { id: row.id }});
  // router.push({
  //   name: 'check-detail',
  //   params: { id: row.id }
  // });
}
// 搜索框绑定的盘点名称
const queryForm = ref({
    name: ''
})

// 按盘点名称搜索的方法
const handleSearch = () => {
  //判断是否为空
  if(!queryForm.value.name){
    ElMessage.warning('请输入盘点名称');
    return;
  }
  const params = {
    name: queryForm.value.name
  }
  listRecords(params).then(res => {
    if (res.code === 200) {
      parentRecords.value = res.data
    }
  })
}

// 重置搜索条件
const handleReset = () => {
  queryForm.value.name = ''
  getRecordsTreeData()
}

onMounted(() => {
  getRecordsTreeData()
  getAllUser()
  getDepartmentTreeData()
})

</script>


<template>
        <!-- 新增搜索框 -->
  <el-form :inline="true" :model="queryForm">
    <el-form-item>
      <el-space>
        <el-input v-model="queryForm.name" placeholder="用户名称" clearable :prefix-icon="Search">
          <template #append>
            <el-button type="primary" :icon="Search" :style="$globalAttribute.primaryButton" @click="handleSearch">
              搜索
            </el-button>
          </template>
        </el-input>
        <el-button type="primary" plain :icon="Refresh" @click="handleReset">
          重置
        </el-button>
        <el-button plain type="primary" :icon="Plus" @click="addRecordsData">
          新增盘点
        </el-button>
      </el-space>
      </el-form-item>
  </el-form>

  <el-dialog v-model="formVisible" :title="title" width="30%">
    <el-form :model="recordForm" label-width="100px">
      <el-form-item label="盘点名称" prop="name"
                    :rules="[ { required: true, message: '请输入盘点名称', trigger: 'blur' }]">
        <el-input v-model="recordForm.name" placeholder="请输入盘点名称"/>
            </el-form-item>
      <el-form-item label="盘点部门" prop="departmentId">
                <!-- 使用级联选择器 -->
              <el-tree-select
                  v-model="recordForm.departmentIds" placeholder="请选择部门"
                  :data="allDepartments"
                  node-key="id"
                  :props="{label:'deptName',children:'children'}"
                  check-strictly
                  multiple
                  :render-after-expand="false"
                  style="width: 100%"
              ></el-tree-select>

            </el-form-item>
      <el-form-item label="计划开始日期" prop="startTime">
              <el-date-picker
                v-model="recordForm.startTime"
                type="date"
                placeholder="计划开始日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
      <el-form-item label="计划结束日期" prop="endTime">
              <el-date-picker
                v-model="recordForm.endTime"
                type="date"
                placeholder="计划结束日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
      <!--
                  <el-form-item label="盘点编号" prop="deptCode">
                      <el-input v-model="recordForm.deptCode" />
                  </el-form-item>

                 <el-form-item label="盘点负责人" prop="managerId">
                      <el-input v-model="recordForm.managerId" />
                  </el-form-item> -->

      <el-form-item label="盘点负责人" prop="taskId">
              <el-select
                v-model="recordForm.taskId"
                clearable
                placeholder="请选择盘点负责人"
                style="width: 100%"
              >
                <el-option
                  v-for="item in allUsers"
                  :key="item.id"
                  :label="item.username"
                  :value="item.id"
                />
              </el-select>

            </el-form-item>
            <div class="dialog-footer">
                <el-button @click="formVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确定</el-button>
            </div>
        </el-form>
    </el-dialog>
      <el-table
        :data="parentRecords"
        row-key="id"
        height="80%"
        style="width: 100%;margin-top: 10px;margin-bottom: 20px;"
        default-expand-all
        table-layout="auto"
       :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column prop="name" label="盘点名称" align="left"/>
        <!--        <el-table-column prop="orderNo" label="盘点编号" align="center"/>-->
        <el-table-column prop="taskName" label="盘点负责人" align="center"/>
        <el-table-column prop="startTime" label="开始时间" align="center"/>
        <el-table-column prop="endTime" label="结束时间" align="center"/>
        <el-table-column label="操作" align="center" width="200">
            <template #default="scope">
              <el-space>
                <el-link type="primary" :icon="Edit" link @click="editRecordData(scope.row)">编辑</el-link>
                <el-link type="primary" :icon="View" link @click="recordDataDetail(scope.row)">详情</el-link>
                <el-popconfirm
                    class="box-item"
                    title="您确定删除吗"
                    placement="bottom"
                    @confirm="deleteRecordData(scope.row)"
                >
                  <template #reference>
                    <el-link type="danger" :icon="Delete" link>删除</el-link>
                  </template>
                </el-popconfirm>

              </el-space>
            </template>
        </el-table-column>
    </el-table>

</template>



<style scoped lang='less'>
    .mb-4 {
        margin-bottom: 1rem;
    }
    .dialog-footer {
        display: flex;
        justify-content: flex-end;
        margin-top: 20px;
    }


    // 添加级联面板样式
    :deep(.cascader-popper) {
        .el-cascader-node:not(.is-leaf) > .el-cascader-node__label {
        color: #409EFF;
        &::after {
            content: '（可选）';
            font-size: 12px;
            color: #999;
        }
        }
    }

</style>

